package com.yyy.tcc.service.compensation;

import java.util.ArrayList;
import java.util.List;

public class CacheCoherencyDemo {
    /**
     * 模拟CPU缓存行的状态
     */
    private enum CacheLineState {
        MODIFIED,  // 已修改（脏）
        EXCLUSIVE, // 独占
        SHARED,    // 共享
        INVALID    // 无效
    }

    /**
     * 模拟CPU缓存行
     */
    private static class CacheLine {
        int value;          // 数据
        CacheLineState state; // 缓存行状态

        public CacheLine(int value, CacheLineState state) {
            this.value = value;
            this.state = state;
        }
    }

    /**
     * 模拟CPU的缓存操作
     */
    private static class CPU {
        private final int id;
        private CacheLine cacheLine;  // CPU的缓存行
        private Bus bus;             // 总线，用于和其他CPU通信

        public CPU(int id, Bus bus) {
            this.id = id;
            this.bus = bus;
        }

        // 写操作
        public void write(int newValue) {
            System.out.println("CPU" + id + " 准备写入值: " + newValue);

            // 1. 发出RFO(Read For Ownership)请求
            bus.requestForOwnership(this);

            // 2. 更新本地缓存
            cacheLine.value = newValue;
            cacheLine.state = CacheLineState.MODIFIED;

            // 3. 通知其他CPU使其缓存失效
            bus.invalidateOtherCaches(this);

            System.out.println("CPU" + id + " 完成写入");
        }

        // 读操作
        public int read() {
            if (cacheLine.state == CacheLineState.INVALID) {
                // 缓存无效，从主内存读取
                System.out.println("CPU" + id + " 缓存无效，从主内存读取");
                cacheLine.value = bus.readFromMainMemory();
                cacheLine.state = CacheLineState.SHARED;
            }

            return cacheLine.value;
        }
    }

    /**
     * 模拟总线，负责CPU间通信和内存访问
     */
    private static class Bus {
        private int mainMemoryValue = 0;  // 主内存中的值
        private List<CPU> cpus = new ArrayList<>();

        // CPU请求独占权
        public void requestForOwnership(CPU requestingCPU) {
            System.out.println("CPU" + requestingCPU.id + " 请求独占权");
            // 使其他CPU缓存失效
            for (CPU cpu : cpus) {
                if (cpu != requestingCPU) {
                    cpu.cacheLine.state = CacheLineState.INVALID;
                }
            }
        }

        // 使其他CPU缓存失效
        public void invalidateOtherCaches(CPU writingCPU) {
            System.out.println("使其他CPU缓存失效");
            for (CPU cpu : cpus) {
                if (cpu != writingCPU) {
                    cpu.cacheLine.state = CacheLineState.INVALID;
                }
            }
        }

        // 从主内存读取
        public int readFromMainMemory() {
            System.out.println("从主内存读取值: " + mainMemoryValue);
            return mainMemoryValue;
        }

        // 写入主内存
        public void writeToMainMemory(int value) {
            mainMemoryValue = value;
            System.out.println("写入主内存: " + value);
        }
    }

    /**
     * 演示缓存一致性协议的工作过程
     */
    public static void main(String[] args) {
        Bus bus = new Bus();

        // 创建两个CPU
        CPU cpu1 = new CPU(1, bus);
        CPU cpu2 = new CPU(2, bus);

        // 初始状态：两个CPU都有共享的缓存
        cpu1.cacheLine = new CacheLine(0, CacheLineState.SHARED);
        cpu2.cacheLine = new CacheLine(0, CacheLineState.SHARED);

        bus.cpus.add(cpu1);
        bus.cpus.add(cpu2);

        // CPU1写入新值
        System.out.println("=== CPU1 写操作 ===");
        cpu1.write(42);

        // CPU2读取值
        System.out.println("\n=== CPU2 读操作 ===");
        int value = cpu2.read();
        System.out.println("CPU2 读取到的值: " + value);
    }
}
